package com.maiji.cloud.aop;

import com.alibaba.fastjson.JSON;
import com.maiji.cloud.config.MyRedisConfig;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.response.BaseMetaResDto;
import com.maiji.cloud.response.community.ComRecsOutputDto;
import com.maiji.cloud.response.login.RecipeResData;
import com.maiji.cloud.response.shopingmall.GoodsResData;
import com.maiji.cloud.response.shopingmall.ShopingOrderResData;
import com.maiji.cloud.utils.RedisUtil;
import com.maiji.cloud.utils.ShareInfoEnum;
import com.maiji.cloud.utils.UUID_MD5;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.LinkedHashMap;
import java.util.List;

@Component
@Aspect
public class WebControllerAop {

    Logger logger = LoggerFactory.getLogger(WebControllerAop.class);
    @Value("${realmName}")
    private String realmName;
    @Autowired
    private RedisTemplate<String, Object> maiji1RedisTemplate;
    @Autowired
    private RedisTemplate<String, Object> maiji2RedisTemplate;
    @Autowired
    private UserInfoService userInfoService;

    @Before(value="execution(* com.maiji.cloud.controller.community.CommunityController.*(..))")
    public void doBeforeOrderSubmit(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String maijiToken = request.getHeader("maijiToken");
        userInfoService.checkToken(maijiToken, true);
    }

    @Before(value="execution(* com.maiji.cloud.controller.login.*.*_query(..))")
    public void doBeforeGetAppUser(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String xId = request.getHeader("maijiToken");
        AppUser appUser = userInfoService.getAppUserByXId(xId);
        RedisUtil.setObject2(maiji1RedisTemplate, MyRedisConfig.REDISDATABASENO, "maijiToken:" + xId, appUser);
        if (maiji2RedisTemplate != null) RedisUtil.setObject2(maiji2RedisTemplate, MyRedisConfig.REDISDATABASENO, "maijiToken:" + xId, appUser);
    }

    @Pointcut("execution(* com.maiji.cloud.controller.shopingmall.GoodsController.*(..))")
    public  void executeService(){}

    @AfterReturning(value="executeService()", returning = "baseDataResDto")
    public void doAfterReturningGoodsResDatas(BaseMetaResDto<List<GoodsResData>> baseDataResDto){
        dealWithList(baseDataResDto.getData(), GoodsResData.class);
    }

    private void dealWithList (List list, Class clazz) {
        if (list == null || list.size() == 0) return;
        list.parallelStream().forEach(bean -> {
            LinkedHashMap map = (LinkedHashMap) bean;
            String uuId = (String) map.get("uuId");
            if (clazz == GoodsResData.class) {
                map.put("webUrl", realmName + ShareInfoEnum.SHARE_GOODS.getWebUrl() + uuId);
                map.put("shareUrl", realmName + ShareInfoEnum.SHARE_GOODS.getShareUrl() + uuId);
                if ((Integer) map.get("isExchange") == 1) {
                    map.put("webUrl2", realmName + ShareInfoEnum.SHARE_GOODS.getWebUrl2() + uuId);
                    map.put("shareUrl2", realmName + ShareInfoEnum.SHARE_GOODS.getShareUrl2() + uuId);
                }
            } else if (clazz == ShopingOrderResData.class) {
                map.put("resultUrl", realmName + "/pages/orderPay/orderPay?uuId=" + uuId);
            }
        });
    }

    /*@Around("execution(* com.maiji.cloud.controller..*(..))")
    public Object doAroundService(ProceedingJoinPoint proceedingJoinPoint){
        String requestId = UUID_MD5.getUUID();
        try {
            Object[] args = proceedingJoinPoint.getArgs();
            logger.info("doAroundService: " + requestId + " ===>> "+proceedingJoinPoint.getSignature().getName() + ": args ===>> " + JSON.toJSONString(args));
            Object object=proceedingJoinPoint.proceed();
            logger.info("doAroundService: " + requestId + " ===>> "+proceedingJoinPoint.getSignature().getName() + ": return ===>> " + JSON.toJSONString(object));
            return object;
        } catch (Throwable throwable) {
            logger.info("doAroundService: " + requestId + " ===>> "+proceedingJoinPoint.getSignature().getName() + ": throwable");
            throwable.printStackTrace();
        }
        return null;
    }*/

}
